package com.example.nio;

import io.netty.channel.ChannelFuture;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author shanchong
 * @date 2021/3/15
 **/
public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        serverSocketChannel.bind(new InetSocketAddress(8000));
        while(true){
            selector.select();
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while(it.hasNext()){
                SelectionKey key = it.next();
                if (key.isValid() && key.isAcceptable()){
                    SocketChannel sc = serverSocketChannel.accept();
                    sc.configureBlocking(false);
                    ByteBuffer buf = ByteBuffer.allocate(1024);
                    buf.put("HTTP/1.1 200\r\n".getBytes());
                    buf.put("Content-Type: text/html\r\n".getBytes());
                    buf.put("Date: Thu, 26 Jul 2018 01:54:53 GMT\r\n".getBytes());
                    buf.put("\r\n".getBytes());
                    buf.put("<html><head><title>Hello</title></head><body><h1>hello world aaaa</h1></body></html>".getBytes());
                    buf.flip();
                    sc.write(buf);
                    sc.shutdownOutput();
                    //sc.close();
                }
            }
        }

    }


}
